<?php

namespace iflow\annotation\Db\Column;

use iflow\annotation\Db\Model;
use iflow\annotation\Db\Table;
use Reflector;

#[\Attribute(\Attribute::TARGET_PROPERTY)]
class PrimaryKeyColumn extends Column {

    public string|array $indexType = ColumnIndexType::PRIMARY;

    public bool $primaryKey  = true;


    public function __construct(
        public string $name = '',
        public string $type = '',
        public int $length = 255,
        public string $description = '',
        public string $defaultValue = '',
        public bool $nullable = false,
        public bool $auto_increment = true,
        public string $classPrimaryKeyField = 'pk'
    ) {}


    public function handle(Reflector $reflector, Table $table, Model $model, array &$args): mixed {
        $result = parent::handle($reflector, $table, $model, $args); // TODO: Change the autogenerated stub
        $this -> setPk($model);
        return $result;
    }


    protected function setPk(Model $model): mixed {
        $columName = $this -> getColumName();

        if (method_exists($model, $this -> classPrimaryKeyField)) {
            return $model -> {$this -> classPrimaryKeyField}($columName);
        }

        if (property_exists($model, $this -> classPrimaryKeyField)) {
            return $model -> {$this -> classPrimaryKeyField} = $columName;
        }

        return null;
    }


}
